package com.gitee.wsl.struct.combine.ext

import com.gitee.wsl.struct.combine.BModifier


/**
 * Conditionally applies the [action] to the receiver [BModifier<E>], if [precondition] is true. Returns the receiver as-is
 * otherwise.
 */
//inline fun <E:BModifier.Element<E>> E.thenIf(
//    precondition: Boolean,
//    action: E.() -> E
//) = if (precondition) action() else this


/**
 * BModifier<E> check bool is FALSE for set params
 */
inline fun <E:BModifier.Element<E>> E.ifFalse(
    value: Boolean,
    crossinline block: E.() -> E
) = thenIf(value, ifFalse = block, ifTrue = { this })

/**
 * BModifier<E> check bool is TRUE for set params
 */
inline fun <E:BModifier.Element<E>> E.ifTrue(
       value: Boolean,
       crossinline block: E.() -> E
) = thenIf(value, ifTrue = block)

/**
 * Calls the given [callback] only if [obj] is not `null`.
 */
inline fun <T : Any,E:BModifier.Element<E>> E.ifNotNull(
       obj: T?,
       callback: E.(T) -> E
): E {
    return if (obj == null) {
        this
    } else {
        callback(obj)
    }
}

/**
 * Apply the [ifTrue] block to the BModifier<E> chain only if the [condition] is `true`, otherwise apply [ifFalse]
 * (nothing additional by default)
 *
 * @return the continued BModifier<E> chain with changes applied, if any.
 */
inline fun <E:BModifier.Element<E>> E.thenIf(
    condition: Boolean,
    ifFalse: E.() -> E = { this },
    ifTrue: E.() -> E
) = then( if (condition) this.ifTrue() else this.ifFalse())

/**
 * Apply the  [block] to the BModifier<E> chain only if the [value] is not null, otherwise apply [ifNull]
 * (nothing additional by default)
 *
 * @return the continued BModifier<E> chain with changes applied, if any.
 */
inline fun <T,E:BModifier.Element<E>> E.thenIfNotNull(
    value: T,
    ifNull: E.() -> E = { this },
    block: E.(T & Any) -> E
): BModifier<E> = then( if (value != null) this.block(value) else this.ifNull() )